package cn.zhiwen.reflectController;

import cn.zhiwen.entity.Student;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo03 {

    public static void main(String[] args) {
        try {
            //获取Class对象
            Class aClass = Class.forName("cn.zhiwen.entity.Student");
            //获取字段
            System.out.println("************获取所有公有的字段********************");
            Field[] fields = aClass.getFields();
            for (Field field : fields) {
                System.out.println(field);
            }

            System.out.println("************获取所有的字段(包括私有、受保护、默认的)********************");
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                System.out.println(declaredField);
            }

            System.out.println("*************获取公有字段**并调用***********************************");
            Field name = aClass.getField("name");
            System.out.println(name);
            //获取对象
            Object o = aClass.getConstructor().newInstance();
            name.set(o, "wuzhiwen");//为Student对象中的name属性赋值--》stu.name = "刘德华"
            //验证
            Student o1 = (Student) o;
            System.out.println(o1.getName());

            System.out.println("**************获取私有字段****并调用********************************");
            Field age = aClass.getDeclaredField("age");
            System.out.println(age);
            //暴力破解
            age.setAccessible(true);
            age.set(o,"123123");
            System.out.println(((Student) o).getAge());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

}
